<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive, onMounted } from 'vue'
import { ElTree, ElInput, ElDivider, ElMessageBox, ElMessage } from 'element-plus'
import { getDepartmentApi, saveUserApi, deleteUserByIdApi } from '@/api/department'
import type { DepartmentItem, DepartmentUserItem } from '@/api/department/types'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { getRoleListApi } from '@/api/role'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import {
  getUserListPage,
  getPageListByOrg,
  registerUserApi,
  updateUserApi,
  delUserApi,
  restPwdApi
} from '@/api/user'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods, setColumn } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getPageListByOrg({
      orgCode: unref(currentNodeKey),
      page: { size: unref(pageSize), current: unref(currentPage) },
      ...unref(searchParams)
    })
    return {
      list: res.result.records || [],
      total: res.result.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await delUserApi(unref(ids))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'departName',
    label: t('userDemo.departmentName'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'realname',
    label: t('userDemo.username')
  },
  {
    field: 'username',
    label: t('userDemo.account')
  },
  {
    field: 'orgCode',
    label: t('userDemo.departmentName'),
    detail: {
      hidden: true
      // slots: {
      //   default: (data: DepartmentUserItem) => {
      //     return <>{data.department.departmentName}</>
      //   }
      // }
    },
    search: {
      hidden: true
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        checkStrictly: true,
        nodeKey: 'orgCode',
        props: {
          label: 'departName'
        }
      },
      optionApi: async () => {
        const res = await getDepartmentApi()
        return res.result
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'roles',
    label: t('userDemo.role'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as DepartmentUserItem
          if (row.roles) {
            const roles = getRoleNames(row.roles)
            return <>{roles}</>
          }
        }
      }
    },
    form: {
      component: 'Select',
      value: [],
      componentProps: {
        multiple: true,
        collapseTags: true,
        maxCollapseTags: 1
      },
      optionApi: async () => {
        const res = await getRoleListApi({})
        return res.result?.map((v) => ({
          label: v.roleName,
          value: v.roleCode
        }))
      }
    }
  },
  {
    field: 'status',
    label: t('menu.status'),
    search: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: any) => {
          return renderTag(data.status)
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: t('userDemo.disable'),
            value: '0'
          },
          {
            label: t('userDemo.enable'),
            value: '1'
          }
        ]
      },
      value: '1'
    },
    table: {
      width: 60,
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElTag type={data.row.status === 0 ? 'danger' : 'success'}>
                {data.row.status === '1' ? t('userDemo.enable') : t('userDemo.disable')}
              </ElTag>
            </>
          )
        }
      }
    }
  },
  {
    field: 'email',
    label: t('userDemo.email'),
    form: {
      component: 'Input'
    },
    search: {
      hidden: true
    }
  },

  {
    field: 'createTime',
    label: t('userDemo.createTime'),
    form: {
      component: 'Input',
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 240,
      slots: {
        default: (data: any) => {
          const row = data.row as DepartmentUserItem
          return (
            <>
              <BaseButton type="primary" onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}
const renderTag = (enable?: boolean) => {
  return <ElTag type={!enable ? 'danger' : 'success'}>{enable ? '启用' : '禁用'}</ElTag>
}
const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
const departmentList = ref<DepartmentItem[]>([])
const fetchDepartment = async () => {
  const res = await getDepartmentApi()
  departmentList.value = res.result
  currentNodeKey.value = ''
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
}
fetchDepartment()

const roles = ref([])

onMounted(async () => {
  try {
    const response = await getRoleListApi({})
    if (response && response.result) {
      roles.value = response.result.map((role) => ({ label: role.roleName, value: role.roleCode }))
    }
  } catch (error) {
    console.error('Failed to load roles:', error)
  }
})

const getRoleNames = (roleCodes) => {
  console.log('getRoleNames', roleCodes)
  return roles.value
    .filter((role) => roleCodes.includes(role.value))
    .map((role) => role.label)
    .join(',')
}

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: DepartmentItem) => {
  // if (data.children) return
  console.log('currentChange', data)
  currentNodeKey.value = data.orgCode
  currentPage.value = 1
  getList()
}

const filterNode = (value: string, data: DepartmentItem) => {
  if (!value) return true
  return data.departName.includes(value)
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<DepartmentUserItem>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)
const restPwdLoading = ref(false)
const ids = ref<string[]>([])

const delData = async (row?: DepartmentUserItem) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: DepartmentUserItem) => v.id) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const restPwd = async (row?: DepartmentUserItem) => {
  ElMessageBox.confirm(t('common.restPwdMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  }).then(async () => {
    const elTableExpose = await getElTableExpose()
    ids.value = row
      ? [row.id]
      : elTableExpose?.getSelectionRows().map((v: DepartmentUserItem) => v.id) || []
    restPwdLoading.value = true
    try {
      await restPwdApi(unref(ids))
      ElMessage.success(t('common.restSuccess'))
    } catch (e) {
    } finally {
      restPwdLoading.value = false
    }
  })
}

const action = (row: DepartmentUserItem, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type

  currentRow.value = { ...row, department: unref(treeEl)?.getCurrentNode() || {} }
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const multipleSelection = ref([])

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res =
        actionType.value === 'edit'
          ? await updateUserApi(formData)
          : await registerUserApi(formData)
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px" style="overflow-y: auto; height: 742px">
      <div class="flex justify-center items-center">
        <div class="flex-1">{{ t('userDemo.departmentList') }}</div>
        <ElInput
          v-model="currentDepartment"
          class="flex-[2]"
          :placeholder="t('userDemo.searchDepartment')"
          clearable
        />
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'departName'
        }"
        :filter-node-method="filterNode"
        @node-click="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.departName" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.departName }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />

      <div class="mb-10px">
        <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
        <!--<BaseButton :loading="delLoading" type="warning" @click="delData()">
          {{ t('exampleDemo.disable') }}
        </BaseButton>-->
        <BaseButton
          :loading="restPwdLoading"
          type="warning"
          @click="restPwd()"
          :disabled="multipleSelection.length > 1"
        >
          {{ t('exampleDemo.restPwd') }}
        </BaseButton>
        <BaseButton :loading="delLoading" type="danger" @click="delData()">
          {{ t('exampleDemo.del') }}
        </BaseButton>
      </div>
      <Table
        @selection-change="handleSelectionChange"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :action-type="actionType"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
